package com.weidong.mybbs.interceptor;

import com.alibaba.fastjson.JSON;
import com.weidong.mybbs.annotation.Permission;
import com.weidong.mybbs.annotation.SkipAuthValid;
import com.weidong.mybbs.entity.SysUser;
import com.weidong.mybbs.service.AuthService;
import com.weidong.mybbs.service.PermissionService;
import com.weidong.mybbs.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Writer;
import java.net.URLEncoder;

@Component
public class PermissionInterceptor implements HandlerInterceptor {

    @Autowired
    private PermissionService permissionService;
    @Autowired
    private AuthService authService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HandlerMethod method = (HandlerMethod)handler;

        if (!method.hasMethodAnnotation(SkipAuthValid.class) && method.hasMethodAnnotation(Permission.class)){
            Permission permission = method.getMethodAnnotation(Permission.class);
            SysUser sysUser = authService.getCurrentUser(request);
            for (String key:permission.keys()) {
                if (permissionService.validPermission(sysUser.getUserId(),key)){
                    return true;
                }
            }
            response.setCharacterEncoding("UTF-8");
            if (!method.hasMethodAnnotation(ResponseBody.class)){
                //获取类注解
                if (method.getBeanType().getAnnotation(RestController.class) == null){
                    response.setContentType(MediaType.TEXT_HTML_VALUE);
                    response.sendRedirect("/error?msg="+ URLEncoder.encode("没有权限访问！","UTF-8")+"&path="+URLEncoder.encode(request.getRequestURI(),"utf-8"));
                    return false;
                }
            }
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            Writer writer = response.getWriter();
            writer.write(JSON.toJSONString(AjaxResult.error(4030,"没有权限访问！path="+request.getRequestURI())));
            writer.close();
            response.setStatus(HttpStatus.FORBIDDEN.value());
            return false;
        }
        return true;

    }
}
